package com.wfg.spring.springRegistrar.FactoryBean;

import com.wfg.spring.springRegistrar.mapper.SelectMapper;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Proxy;

/**
 * @author: 王富贵
 * @description:
 * @createTime: 2023/11/05 18:07
 */
public class SelectMapperFactoryBean implements FactoryBean {

    private String className = "";

    public SelectMapperFactoryBean(String className) {
        this.className = className;
    }

    /**
     * 使用className创建FactoryBean，反射创建接口实现
     */
    @Override
    public Object getObject() throws ClassNotFoundException {
        Class<?> aClass = Class.forName(className);
        return Proxy.newProxyInstance(aClass.getClassLoader(), new Class[]{SelectMapper.class},
                (proxy, method, args) -> {
                    String className = method.getDeclaringClass().getName();
                    String methodName = method.getName();
                    // 类名+方法名可以做一个请求缓存。将最后生成的类或者逻辑缓存起来，用于下次使用
                    String cacheKey = className + methodName;
                    if ("selectOne".equals(method.getName())) {
                        System.out.println("代理对象执行selectOne方法");
                        return "selectOne";
                    } else if ("batchSelect".equals(method.getName())) {
                        System.out.println("代理对象执行batchSelect方法");
                        return "batchSelect";
                    }
                    return proxy;
                });
    }

    @Override
    public Class<?> getObjectType() {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
